package fr.inria.arles.temperatureManagement.android;

import static fr.inria.arles.temperatureManagement.Constants.*;
import static fr.inria.arles.temperatureManagement.utility.DeviceFinder.*;

import org.cybergarage.upnp.ControlPoint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import fr.inria.arles.temperatureManagement.communication.QueryProcessorCommunicator;
import static fr.inria.arles.temperatureManagement.android.DeviceProvider.*;

/**
 * 
 * Activity to display login form and send an authentication query containing
 * the entered information to the query processor.
 * 
 * @author ajay chhatwal
 */
public class Login extends Activity {

	private ControlPoint cp;
	/** Handles event: Button loginB clicked. */
	private final OnClickListener loginBClicked = new OnClickListener() {

		public void onClick(View v) {

			Intent intent;
			try {

				EditText usernameET = ((EditText) findViewById(R.id.usernameET));
				EditText passwordET = ((EditText) findViewById(R.id.passwordET));
				EditText partitionET = ((EditText) findViewById(R.id.partitionET));

				String username = usernameET.getText().toString();
				String password = passwordET.getText().toString();
				String partition = partitionET.getText().toString();

				String ID = QueryProcessorCommunicator.authenticate(
						queryProcessor, username, password, partition);
				if (ID.equals("-1")) {
					intent = new Intent(Login.this, LoginFail.class);
				} else {
					intent = new Intent(Login.this, Home.class);
					intent.putExtra("username", username);
					intent.putExtra("partition", partition);
					intent.putExtra("ID", ID);
				}
				startActivity(intent);
			} catch (Exception e) {
				Context context = getApplicationContext();
				CharSequence text = "Exception:" + e;
				int duration = Toast.LENGTH_LONG;

				Toast toast = Toast.makeText(context, text, duration);
				toast.show();
				Log.e("Exception", e + "", e);
			}
		}
	};

	/**
	 * Called when the activity is first created.
	 * 
	 * @param savedInstanceState
	 *            the saved instance state
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		try {

			WifiManager wMan = (WifiManager) getApplicationContext()
					.getSystemService(Context.WIFI_SERVICE);
			WifiManager.MulticastLock wifiMulticastLock = wMan
					.createMulticastLock("UPnP");
			wifiMulticastLock.acquire();
			if (cp == null) {
				cp = new ControlPoint();
				cp.start();
			}
			if (queryProcessor == null) {
				queryProcessor = searchForDevice(cp, QUERY_PROCESSOR_DEVICE);
			}
			if (tempManager == null) {
				tempManager = searchForDevice(cp, TEMPERATURE_MANAGER_DEVICE);
			}

		} catch (Exception e) {
			Context context = getApplicationContext();
			CharSequence text = "Exception:" + e;
			int duration = Toast.LENGTH_LONG;

			Toast toast = Toast.makeText(context, text, duration);
			toast.show();

			Log.e("Exception", e + "", e);
		}

		Button loginB = (Button) findViewById(R.id.loginB);
		loginB.setOnClickListener(loginBClicked);
	}

	/**
	 * Called when the activity is first created.
	 * 
	 * @param menu
	 *            the Menu to be populated
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.options_menu, menu);
		return true;
	}

	/**
	 * Handles item selections
	 * 
	 * @param item
	 *            the selected MenuItem
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.settings:
			Intent intent = new Intent(this, Settings.class);
			startActivity(intent);
			return true;
		case R.id.exit:
			moveTaskToBack(true);
			return true;
		}
		return false;
	}

}